package com.mercury.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.mercury.base.manager.RedisManager;
import com.mercury.security.constants.SystemConstants;
import com.mercury.system.api.model.entity.SysPermission;
import com.mercury.system.biz.mapper.SysPermissionMapper;
import com.mercury.system.biz.service.ISysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限处理
 *
 * @author mercury
 */
@Service
@Slf4j
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {


    @Resource
    private RedisManager redisManager;

    @Override
    public void refreshPermRolesRules() {
        redisManager.remove(new HashSet<>(Collections.singleton(SystemConstants.URL_PERM_ROLES_KEY)));
        List<SysPermission> permissions = this.listPermRoles();
        if (!CollectionUtils.isEmpty(permissions)) {
            List<SysPermission> urlPermList = permissions.stream()
                    .filter(item -> StrUtil.isNotBlank(item.getUrlPerm()))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(urlPermList)) {
                Map<String, List<String>> urlPermRoles = new HashMap<>(16);
                urlPermList.forEach(item -> {
                    String perm = item.getUrlPerm();
                    List<String> roles = item.getRoles();
                    urlPermRoles.put(perm, roles);
                });
                redisManager.hPutAll(SystemConstants.URL_PERM_ROLES_KEY, urlPermRoles);
            }
        }
    }

    public List<SysPermission> listPermRoles() {
        return this.baseMapper.selectList(new LambdaQueryWrapper<>());
    }
}
